<template>
    <div class="box">
        <el-button @click="getPdf">下载PDF</el-button>
        <el-button @click="getPdf('online')">在线查看PDF</el-button>
        <!-- <div style="height:0;overflow:hidden"> -->
        <div id="pdfDom">
            <Cover :pdfHeight="pdfHeight" />
            <TableSign :pdfHeight="pdfHeight" />
            <List :pdfHeight="pdfHeight" />
        </div>
        <!-- </div> -->
    </div>
</template>

<script>
import { Button } from 'element-ui'
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import Cover from './Cover.vue'
import TableSign from './TableSign.vue'
import List from './List.vue'
export default {
    components: { Cover, TableSign, List, ElButton: Button },
    data () {
        return {
            pdfHeight: 1415,
            pdfWidth: 1000,
            dataList: [],
            signList: []
        }
    },
    mounted () {
    },
    methods: {
        getPdf (type) {
            const title = document.title
            const [widthA4, heightA4] = [this.pdfWidth, this.pdfHeight]
            // const [widthA4, heightA4] = [592.28, 841.89]
            html2Canvas(document.querySelector('#pdfDom'), {
                allowTaint: true
            }).then(function (canvas) {
                const contentWidth = canvas.width
                const contentHeight = canvas.height
                const pageHeight = contentWidth / widthA4 * heightA4
                let leftHeight = contentHeight
                let position = 0
                const imgWidth = widthA4
                const imgHeight = widthA4 / contentWidth * contentHeight
                const pageData = canvas.toDataURL('image/jpeg', 1.0)
                const PDF = new JsPDF('', 'px', [widthA4, heightA4])
                // const PDF = new JsPDF('', 'pt', 'a4')
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight
                        position -= heightA4
                        if (leftHeight > 0) {
                            PDF.addPage()
                        }
                    }
                }
                if (type) {
                    const doc = PDF.output('bloburi')
                    window.open(doc)
                } else {
                    PDF.save(title + '.pdf')
                }
            })
        }

    }
}
</script>

<style lang="less" scoped>
#pdfDom {
    width: 1000px;
    margin: auto;
}
</style>
